package com.atguigu.eduservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.eduservice.entity.EduTeacher;
import com.atguigu.eduservice.entity.vo.TeachQuery;
import com.atguigu.eduservice.service.EduTeacherService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author ZhanK
 * @since 2022-01-27
 */
@Api(description ="讲师模块管理")
@RestController
@RequestMapping("/eduservice/edu-teacher")
public class EduTeacherController {
    @Autowired
    private EduTeacherService eduTeacherService;

    @ApiOperation(value = "所有讲师列表")
    @CrossOrigin
    @GetMapping(value = "findAll")
    public R findAllTeacher() {

        List<EduTeacher> list = eduTeacherService.list(null);

        return R.ok().data("items", list);
    }

    @ApiOperation(value = "逻辑删除讲师")
    @CrossOrigin
    @DeleteMapping("{id}")
    public R deleteTeacher(@ApiParam(name = "id", value = "讲师id", required = true) @PathVariable String id) {
        //Mybaits-plus中的IService接口remove 方法一直返回true,因为remove方法实现在版本3.3.0之前remove方法调用的是delBool方法,
        // 这个方法的逻辑是只要程序运行没有报错remove方法就会一直返回true。将Mybaits-plus版本提升到3.3.0或3.3.0以上,因为在最新版本3.3.0已经修复，
        // SqlHelper中已经移除delBool方法，save update remove全部都使用retBool方法判断逻辑。
        boolean removeById = eduTeacherService.removeById(id);
        if (removeById) {
            return R.ok().data("items", removeById);

        } else
            return R.error().data("items", removeById);
    }

    @ApiOperation(value = "分页讲师列表")
    @GetMapping(value = ("{page}/{limit}"))
    public R pageList(@ApiParam(name = "page", value = "当前页码", required = true) @PathVariable Long page,
                      @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable Long limit) {

        Page<EduTeacher> pageParam = new Page<>(page, limit);
        eduTeacherService.page(pageParam, null);
        List<EduTeacher> records = pageParam.getRecords();
        long total = pageParam.getTotal();
        return R.ok().data("total", total).data("rows", records);

    }

    //4.条件查询分页方法
    @ApiOperation(value = "条件查询分页方法")
    @PostMapping("pageTeacherCondition/{current}/{limit}")
    @CrossOrigin //跨域问题，不加这个标签报错 No 'Access-Control-Allow-Origin'，也可以通过网关处理
    public R pageTeacherCondition(@PathVariable Long current,
                                  @PathVariable Long limit,

                                  @RequestBody(required = false) TeachQuery teachQuery)
    // @RequestBody只能接受Json的数据且只支持post请求，其实就是对应ajax的提交，然后将它封装到javabean，
    // 有时候获取不了表单的提交可能是这个问题，如果遇到了可以把表单提交通过js写到ajax里面去提交且格式设置为json 应该就没问题。
    // get请求肯定是获取不到的。直接用pojo对象获取就行。
    {
        //创建page
        Page<EduTeacher> pageCondition = new Page<>(current, limit);

        //QueryWrapper,构建
        QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>();

        if (StringUtils.isEmpty(teachQuery)) {   //如果传入的参数为空就调用这个
            //调用方法，实现分页查询
            eduTeacherService.page(pageCondition, null);
            long total = pageCondition.getTotal();//获取总记录数
            List<EduTeacher> records = pageCondition.getRecords();//获取分页后的list集合
            HashMap<String, Object> map = new HashMap<>();
            map.put("total", total);
            map.put("rows", records);
            return R.ok().data(map);
        }
        //多条件组合查询，动态sql
        String name = teachQuery.getName();
        Integer level = teachQuery.getLevel();
        String begin = teachQuery.getBegin();
        String end = teachQuery.getEnd();
        //判断条件是否为空，拼接条件
        if (!StringUtils.isEmpty(level)) {
            wrapper.eq("level", level);
        }
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(begin)) {
            wrapper.ge("gmt_create", begin);
        }
        if (!StringUtils.isEmpty(end)) {
            wrapper.le("gmt_create", end);
        }

        wrapper.orderByDesc("gmt_create");//根据创建时间降序排列

        //调用方法，实现分页查询
        eduTeacherService.page(pageCondition, wrapper);

        long total = pageCondition.getTotal();//获取总记录数
        List<EduTeacher> records = pageCondition.getRecords();//获取分页后的list集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("rows", records);

        return R.ok().data(map);
    }

    @ApiOperation("添加教师")
    @CrossOrigin
    @PostMapping("addTeacher")
    public R addTeacher(@RequestBody EduTeacher eduTeacher) {

        try {
            boolean save = eduTeacherService.save(eduTeacher);
            if (save) {
                return R.ok();
            } else
                return R.error();
        } catch (Exception e) {
            throw new GuliException(20001, "添加失败，用户名输入格式错误或者已存在!");
        }

    }

    @ApiOperation("根据ID查询教师")
    @GetMapping("getTeacher/{id}")
    @CrossOrigin
    public R getTeacher(@PathVariable String id) {

//        try {  //测试自定义异常，如果是自己页面抛出会优先捕获并打印异常
//            int a = 10/0;
//        } catch (Exception e) {
//           throw new GuliException(20001,"执行了自定义异常GuliException！！！！！");
//        }
        EduTeacher eduTeacher = eduTeacherService.getById(id);
        return R.ok().data("teacher", eduTeacher);
    }

    @ApiOperation("修改教师")
    @CrossOrigin
    @PostMapping("updateTeacher")
    public R updateTeacher(@RequestBody EduTeacher eduTeacher) {

        boolean b = eduTeacherService.updateById(eduTeacher);
        if (b) {
            return R.ok();
        } else
            return R.error();
    }


}

